#include "ptcache.h"


Point_Cache::Point_Cache()
{
	m_nAllocated = m_nCount = 0;
	m_pPoints = NULL;
}
Point_Cache::~Point_Cache()
{
	free(m_pPoints);
}

// Construct from an ICAD point array
RC Point_Cache::YieldPoints(int * nverts_p,C3Point** vertex_pp)
{
	RC rc = SUCCESS;
	if (nverts_p)
		*nverts_p = m_nCount;
	else
		rc = E_BadInput;
	if (!vertex_pp)
		rc = E_BadInput;
	else
	{
		*vertex_pp=new  C3Point[m_nCount];
		C3Point*lp=*vertex_pp;
		for(int i=0;i<m_nCount;i++)
		{
			lp->SetX(m_pPoints[i][0]);
			lp->SetY(m_pPoints[i][1]);
			lp->SetZ(m_pPoints[i][2]);
			lp++;
		}
	}
	// Reset
	free(m_pPoints);
	m_pPoints = NULL;
	m_nCount = m_nAllocated = 0;
	RETURN_RC(Point_Cache::YieldPoints, rc);
}

// Make room for an additional point
RC Point_Cache::MakeRoom()
{
	RC rc = SUCCESS;
	if (m_nAllocated <= m_nCount)
	{
		m_nAllocated += 20;
		if (m_pPoints)
			m_pPoints = (C3Point*)realloc(m_pPoints, m_nAllocated * sizeof(C3Point)); 
		else
			m_pPoints = (C3Point*)calloc(m_nAllocated, sizeof(C3Point));
		if (rc = ALLOC_FAIL(m_pPoints))
			QUIT
	}
exit:
	RETURN_RC(Point_Cache::MakeRoom, rc);
}

// Accept a point
RC Point_Cache::Accept(const C3Point& Point,double rDenominator)
{
	C3Point P = Point;
	RC rc = MakeRoom();
	if (rc)
		QUIT
	m_pPoints[m_nCount]=P;
	m_nCount++;
//	RptToSds(P, m_pPoints[m_nCount++]);
exit:
	RETURN_RC(Point_Cache::Accept, rc);
}

// Accept a point
RC Point_Cache::Add(C3Point point)
{
	RC rc = MakeRoom();
	if (rc)
		QUIT
	// Add the point
	m_pPoints[m_nCount]=point;
	m_nCount++;
exit:
	RETURN_RC(Point_Cache::Add, rc);
}